package com.activiti.z_six.controller;

import com.activiti.z_six.SecurityUtil;
import com.activiti.z_six.entity.taskAssignee.AssigneeUserEntity;
import com.activiti.z_six.entity.taskAssignee.FlowElementAttrs;
import com.activiti.z_six.entity.taskAssignee.OvProcessInstance;
import com.activiti.z_six.mapper.taskAssigneeMapper.FlowElementAttrsMapper;
import com.activiti.z_six.mapper.taskAssigneeMapper.OvProcessInstanceMapper;
import com.activiti.z_six.security.RedisUtils;
import com.activiti.z_six.service.AssigneeUserService;
import com.activiti.z_six.service.ProcessDefinitionService;
import com.activiti.z_six.util.AjaxResponse;
import com.activiti.z_six.util.SystemConfig;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.RepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

@RestController
public class TaskAssigneeController {
    @Autowired
    private AssigneeUserService assigneeUserService;
    @Autowired
    private ProcessDefinitionService processDefinitionService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SecurityUtil securityUtil;
    @Autowired //流程实例服务
    private OvProcessInstanceMapper ovProcessInstanceMapper;
    @Autowired //流程发布信息服务
    private RepositoryService repositoryService;
    @Autowired
    private FlowElementAttrsMapper flowElementAttrsMapper;

    private Long expireTime=Long.parseLong("360000") ;
    @GetMapping("/as/getAssigneeUserWithTaskId")
    public AjaxResponse getAssigneeUserWithTaskId(HttpServletResponse response,
                                                  @RequestParam("usertaskid") String usertaskid){
        try{
            List<AssigneeUserEntity> assigneeUserEntityList=assigneeUserService.getAssigneeUserWithTaskKey(usertaskid);

            return AjaxResponse.AjaxData(SystemConfig.ResponseCode.SUCCESS.getCode(),
                    SystemConfig.ResponseCode.SUCCESS.getDesc(), assigneeUserEntityList);
        }
        catch (Exception ex){
            return AjaxResponse.AjaxData(SystemConfig.ResponseCode.ERROR.getCode(),
                    "查询失败", ex.toString());
        }
    }
    @PostMapping("/as/setAssigneeUser")
    public AjaxResponse setAssigneeUser(@RequestBody JSONObject param){
        JSONArray userlist = param.getJSONArray("userlist");
        String usertaskid=param.getString("usertaskid");
        //如果redis中已经存在，先删除
        if(redisUtils.exists(usertaskid)){
            redisUtils.remove(usertaskid);
        }
        //写入redis
        redisUtils.set(usertaskid,userlist.toString(),expireTime);

        return AjaxResponse.AjaxData(SystemConfig.ResponseCode.SUCCESS.getCode(),
                SystemConfig.ResponseCode.SUCCESS.getDesc(), "设置成功");
    }
    @PostMapping("/as/setFlowElementAttrs")
    public AjaxResponse setFlowElementAttrs(@RequestBody JSONObject param){
        String redisKey=param.getString("redisKey");
        String attrValue=param.getString("attrKey");
        if(redisUtils.exists(redisKey)){
            redisUtils.remove(redisKey);
        }
        redisUtils.set(redisKey,attrValue);
        return AjaxResponse.AjaxData(SystemConfig.ResponseCode.SUCCESS.getCode(),
                SystemConfig.ResponseCode.SUCCESS.getDesc(), "设置成功");
    }
    @GetMapping("/as/getFormElement")
    public AjaxResponse getFormElement(HttpServletResponse response,
                                       @RequestParam("process_key") String process_key){
        HashMap<String,Object> hashMap=new HashMap<>();
        //获取当前登录用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username=authentication.getName();
        securityUtil.logInAs(username);

        //获取流程模版信息
        OvProcessInstance ovProcessInstance=ovProcessInstanceMapper.getProcessInsLastVersion(process_key);
        BpmnModel bpmnModel = repositoryService.getBpmnModel(ovProcessInstance.getId_());
        //获取流程信息
        Process process=bpmnModel.getProcesses().get(0);
        StartEvent startEvent=(StartEvent)process.getInitialFlowElement();
        List<SequenceFlow> outgoingFlows = startEvent.getOutgoingFlows();
        //获取UserTask类型数据
        UserTask userTask = (UserTask) outgoingFlows.get(0).getTargetFlowElement();
        FlowElementAttrs flowElementAttrs=flowElementAttrsMapper.getFlowElementAttrs(userTask.getId());

        return AjaxResponse.AjaxData(SystemConfig.ResponseCode.SUCCESS.getCode(),
                SystemConfig.ResponseCode.SUCCESS.getDesc(), flowElementAttrs);
    }
    @GetMapping("/as/getFlowElementAttrs")
    public AjaxResponse getFlowElementAttrs(HttpServletResponse response,
                                            @RequestParam("usertaskid") String usertaskid){
        HashMap<String,Object> hashMap=new HashMap<>();
        FlowElementAttrs flowElementAttrs=processDefinitionService.getFlowElementAttrs(usertaskid);
        if(flowElementAttrs==null) {
            if (redisUtils.exists(usertaskid + "_returnWay")) {
                hashMap.put("returnWay", redisUtils.get(usertaskid + "_returnWay"));
            } else {
                hashMap.put("returnWay", "none");
            }
            if (redisUtils.exists(usertaskid + "_runWay")) {
                hashMap.put("runWay", redisUtils.get(usertaskid + "_runWay"));
            } else {
                hashMap.put("runWay", "none");
            }
            if (redisUtils.exists(usertaskid + "_jumpWay")) {
                hashMap.put("jumpWay", redisUtils.get(usertaskid + "_jumpWay"));
            } else {
                hashMap.put("jumpWay", "none");
            }
            if (redisUtils.exists(usertaskid + "_ccWay")) {
                hashMap.put("ccWay", redisUtils.get(usertaskid + "_ccWay"));
            } else {
                hashMap.put("ccWay", "none");
            }
            if (redisUtils.exists(usertaskid + "_autoCCWay")) {
                hashMap.put("autoCCWay", redisUtils.get(usertaskid + "_autoCCWay"));
            } else {
                hashMap.put("autoCCWay", "none");
            }
            if (redisUtils.exists(usertaskid + "_transfer")) {
                hashMap.put("transfer", redisUtils.get(usertaskid + "_transfer"));
            }
            else{
                hashMap.put("transfer", "0");
            }
            if (redisUtils.exists(usertaskid + "_countersign")) {
                hashMap.put("countersign", redisUtils.get(usertaskid + "_countersign"));
            }
            else{
                hashMap.put("countersign", "0");
            }
            if (redisUtils.exists(usertaskid + "_endTask")) {
                hashMap.put("endTask", redisUtils.get(usertaskid + "_endTask"));
            }
            else{
                hashMap.put("endTask", "0");
            }
            if (redisUtils.exists(usertaskid + "_refuse")) {
                hashMap.put("refuse", redisUtils.get(usertaskid + "_refuse"));
            }
            else{
                hashMap.put("refuse", "0");
            }
        }
        else{
            hashMap.put("returnWay", flowElementAttrs.getReturnWay());
            hashMap.put("runWay", flowElementAttrs.getRunWay());
            hashMap.put("jumpWay", flowElementAttrs.getJumpWay());
            hashMap.put("ccWay", flowElementAttrs.getCcWay());
            hashMap.put("autoCCWay", flowElementAttrs.getAutoCCWay());
            hashMap.put("transfer", flowElementAttrs.getTransfer().toString());
            hashMap.put("countersign", flowElementAttrs.getCountersign().toString());
            hashMap.put("endTask", flowElementAttrs.getEndTask().toString());
            hashMap.put("refuse",flowElementAttrs.getRefuse().toString());
        }
        return AjaxResponse.AjaxData(SystemConfig.ResponseCode.SUCCESS.getCode(),
                SystemConfig.ResponseCode.SUCCESS.getDesc(), hashMap);
    }
    @PostMapping("/as/deleteAssigneeUser")
    public AjaxResponse deleteAssigneeUser(@RequestBody JSONObject param){
        String usertaskid=param.getString("usertaskid");
        String username=param.getString("username");
        return assigneeUserService.deleteAssigneeUser(usertaskid,username);
    }
}
